package com.yozinga.service;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Logger;

import android.app.Activity;
import android.content.Context;
import android.media.MediaScannerConnection;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.widget.LinearLayout;

import com.yozinga.util.MemoryStatus;

public class DealImageDownload extends AsyncTask<String, String, String>{

	File myDirectory ;
	MediaScannerConnection mScanner;
	String imageIDs;
	String className;
	LinearLayout addingLayout,placeHolderlayouts;
	public static final int DID_START = 0;
	public static final int DID_ERROR = 1;
	public static final int DID_SUCCEED = 2;
	//static Handler responseHanlder;
	int totalSize;
	int downoadedPercent ;
	boolean write; 
	File file = null;
	FileOutputStream fileOutput = null;
	String fileName = "varunimage.jpg"; 
	DataOutputStream printout;	
	Context context;
	Activity mActivity;
	@Override
	protected String doInBackground(String... params) {
		String path = null;
		for (String url : params){
			try
			{
				
				HttpURLConnection conn = null;
				URL myurl = null ;

				Log.i("Today","Download URl is:"+myurl);
				conn = (HttpURLConnection) myurl.openConnection();
				conn.setDoInput(true); 
				conn.setDoOutput(true);
				conn.setUseCaches(false);
				conn.setConnectTimeout(6000);
				conn.setRequestMethod("GET");
				try {
					printout = new DataOutputStream(conn.getOutputStream());
					printout.flush();
					printout.close();
					if(conn.getResponseCode()==-1){
						path = "service error";
					}
				}
				catch (IOException e) {
					e.printStackTrace();
				}

				if(conn.getResponseCode()==302 || conn.getResponseCode()==400 ){
					Log.i("Today","Error: 302 or 400");
					path = "service error";
				}
				else if(conn.getResponseCode() == 503){
					path = "system maintenance";
				}
				else{		
					
					String headers = conn.getHeaderFields().toString();
					Log.i("Today","Request for Output "+headers); 
					
					
					//String s = headers.substring(headers.indexOf("filename=")+9);
					//fileName = s.substring(0, s.indexOf(']'));
					
					//String extension = fileName.substring(fileName.length()-4, fileName.length());
					
					try{
						totalSize = conn.getContentLength();
						long getAvailableExternalMemorySize = MemoryStatus.getAvailableExternalMemorySize();
						Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
						if(isSDPresent && getAvailableExternalMemorySize >= totalSize)
						{
							String sdcard = Environment.getExternalStorageDirectory()+"/DCIM/yozinga";
							if(!new File(sdcard).exists()){
								new File(sdcard).mkdirs();
							}
							path =sdcard+File.separator+ "Item"+System.currentTimeMillis()+".jpg" ;
							file = new File(path);
							fileOutput = new FileOutputStream(file);
							write = true;
						}
						if(write)
						{
							InputStream inputStream = conn.getInputStream();
							byte[] buffer = new byte[15*1024];
							int bufferLength = 0;
							int buffercount=0;//used to store a temporary size of the buffer
							while ( (bufferLength = inputStream.read(buffer)) >= 0 ) 
							{
								buffercount = buffercount+bufferLength;
								fileOutput.write(buffer, 0, bufferLength);
							}
							if(isCancelled()) break;
							if(className == null)
							{
								//savingImage(path);
							}
							else
							{
								//openDeficiencysavingImage(path);
							}
						//	Logger.i("Today","While complete");
							inputStream = null;
							fileOutput.close();
						}
						else
						{
							//Message   message = Message.obtain(responseHanlder,DID_SUCCEED, "Insufficient free space to download this content.");
							//responseHanlder.sendMessage(message); 
						}
					}
					catch(FileNotFoundException eFileNotFoundException)
					{
						eFileNotFoundException.printStackTrace();
					}
					catch (MalformedURLException e) 
					{
						e.printStackTrace();
					}
					catch (IOException e)
					{
						e.printStackTrace();
					}
					catch(Exception exception)
					{
						exception.printStackTrace();
					}
					conn.disconnect(); 
					conn.getInputStream().close();
				}
			}
			catch(IOException ioException)
			{
				//Log.i("RGT","Exception is: "+ioException.getMessage());
			}
			catch(Exception e)
			{
				//Log.i("RGT","Exception is: "+e.getMessage());
			}
		}
		return path;
	}



}
